package com.sig.formes;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;

import android.opengl.GLES20;
import android.util.Log;

import com.sig.opengl.MyGLRenderer;

public class Layer extends Forme {

	public String type;
	private List<Forme> _formes = new ArrayList<Forme>();

	public Layer Border = null;
	public boolean border_enable;

	LayerParam param= new LayerParam();

	//////////////////:CONSTRUCTEUR://///////////////////////////////
	public Layer()
	{
		this.type = new String();
		if(border_enable)
			createBorderLayer();
	}
	public Layer(float []color,String type, LayerParam p)
	{
		this(color,type);
		this.param = p;
	}
	public Layer(String type , float []color, List<Polyedre> formes)
	{
		this(color,type);
		this._formes.addAll(formes);
	}

	public Layer(float[] color, String type2) {
		this();
		this.type=type2;
		this.color = color;
	}

	///////////////////////////////:GESTION DES BORDURES:////////////////////////////



	/////////////////////:GETTERS AND SETTERS:////////////////////////

	private int getTriangleSize()
	{
		//calcul de la taille totale du layer
		int nb_triangle=0;

		for(Forme p  : this._formes)
		{
			if(p != null)
			{
				if(p instanceof Localisator)
					Log.e("localisation","get Localisator ");
				nb_triangle+=p.getTriangles().size();
			}
		}
		return nb_triangle;
	}


	public void add_Forme(Forme f)
	{
		if(f !=null)
		{
			this._formes.add(f);
			if(f instanceof com.sig.formes.Segment)
			{
				if(Border != null)
				{
					Border.add_Forme(((Segment)f).getBorder1());
					Border.add_Forme(((Segment)f).getBorder2());
				}
				else
				{
					createBorderLayer();
				}
			}
		}
		else 
		{
			Log.e("layer","erreur tentative d'ajout de forme null!!");
		}
	}

	public void add_Forme(List<Forme> formes) {
		for(Forme f : formes)
		{
			Log.e("Layer",formes.toString());
			this.add_Forme(f);
		}
	}


	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public LayerParam getParam() {
		return param;
	}
	public void setParam(LayerParam param) {
		this.param = param;
	}

	////////////////////////////:OPENGL:///////////////////////////////////////

	private final String vertexShaderCode =

			// This matrix member variable provides a hook to manipulate
			// the coordinates of objects that use this vertex shader.
			"uniform mat4 uMVPMatrix;   \n" +

		    "attribute vec4 vPosition;  \n" +
		    "void main(){               \n" +
		    // The matrix must be included as part of gl_Position
		    // Note that the uMVPMatrix factor *must be first* in order
		    // for the matrix multiplication product to be correct.
		    " gl_Position = uMVPMatrix * vPosition; \n" +

		    "}  \n";

	private final String fragmentShaderCode =
			"precision mediump float;" +
					"uniform vec4 vColor;" +
					"void main() {" +
					"  gl_FragColor = vColor;" +
					"}";

	private FloatBuffer vertexBuffer;
	private int mProgram;
	private int mPositionHandle;
	private int mColorHandle;
	private int mMVPMatrixHandle;

	// number of coordinates per vertex in this array
	static final int COORDS_PER_VERTEX = 3;

	private int vertexCount;
	private int vertexStride;

	/**
	 * @author trt
	 *  affectation des differente variable opengl
	 */
	protected void creer(){

		//differente de varaibale pour le calcule de la taille
		int triangleCoordsLength = 9;

		int sizeOfFloat = 4;

		int nb_triangle = getTriangleSize();

		int buffer_size = triangleCoordsLength * nb_triangle * sizeOfFloat;
		if(!border_enable)
		{
			if(Border == null)
				createBorderLayer();
			//on ajoute les Triangles des bordures
			buffer_size += this.Border.getTriangleSize();
		}
		//allocation du buffer
		ByteBuffer bb = ByteBuffer.allocateDirect(
				// (number of coordinate values * 4 bytes per float)
				buffer_size);

		// use the device hardware's native byte order
		bb.order(ByteOrder.nativeOrder());
		vertexBuffer = bb.asFloatBuffer();

		mProgram = GLES20.glCreateProgram();             // create empty OpenGL Program

		//pour chaque polyedre valide
		for(Forme p : this._formes){
			//ajout de ces triangles
			for(Triangle t : p.getTriangles())
			{

				float[] triangleCoords = t.getTriangleCoords();

				// initialize vertex byte buffer for shape coordinates


				// create a floating point buffer from the ByteBuffer

				// add the coordinates to the FloatBuffer
				vertexBuffer.put(triangleCoords);
				// set the buffer to read the first coordinate
			}
		}

		vertexBuffer.position(0);

		// prepare shaders and OpenGL program
		int vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER,
				vertexShaderCode);
		int fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,
				fragmentShaderCode);

		GLES20.glAttachShader(mProgram, vertexShader);   // add the vertex shader to program
		GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
		GLES20.glLinkProgram(mProgram);                  // create OpenGL program executables


		vertexCount = triangleCoordsLength / COORDS_PER_VERTEX * nb_triangle;
		vertexStride = COORDS_PER_VERTEX * sizeOfFloat; // 4 bytes per vertex

	}

	@Override
	public void draw(float[] mvpMatrix) {

		//creation et mise des coordonnee dans le buffer
		if(! cree)
		{
			creer();
			this.cree = true;
		}

		//code opengl
		super.draw(mvpMatrix);

		GLES20.glUseProgram(mProgram);

		//allocation vertex array

		// get handle to vertex shader's vPosition member
		mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");

		// Enable a handle to the triangle vertices
		GLES20.glEnableVertexAttribArray(mPositionHandle);

		// Prepare the triangle coordinate data
		GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
				GLES20.GL_FLOAT, false,
				vertexStride, vertexBuffer);

		// get handle to fragment shader's vColor member
		mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");

		// Set color for drawing the triangle
		GLES20.glUniform4fv(mColorHandle, 1, getColor(), 0);

		// get handle to shape's transformation matrix
		mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
		MyGLRenderer.checkGlError("glGetUniformLocation");

		// Apply the projection and view transformation
		GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
		MyGLRenderer.checkGlError("glUniformMatrix4fv");

		// Draw the triangle
		GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);

		// Disable vertex array
		GLES20.glDisableVertexAttribArray(mPositionHandle);

	}

	@Override
	public void recreer() {
		super.recreer();

	}
	@Override
	public List<Triangle> getTriangles() {
		List<Triangle> res = new ArrayList<Triangle>();
		for(Forme f : _formes)
		{
			res.addAll(f.getTriangles());
		}
		return res;
	}

	private void createBorderLayer()
	{
		this.Border = new Layer(Segment.BORDER_COLOR, "border");
		if(this._formes != null)
		{
			for(Forme f : this._formes)
			{
				if(f instanceof com.sig.formes.Segment)
				{
					Border.add_Forme(((Segment) f).getBorder1());
					Border.add_Forme(((Segment) f).getBorder2());
				}
			}
		}
	}
	public List<Forme> getFormes() {
		return this._formes;
	}

}
